import json

from django.shortcuts import render

# Create your views here.
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets
from django.http import HttpResponse, JsonResponse
from django.core.exceptions import ValidationError
from promptAdmin.prompt_app.services.prompt_generate import s_start_prompt, s_store_file, s_get_chat_chain, \
    s_store_file_ollama, s_get_chat_chain_ollama, \
    s_store_file_ollama_chroma, s_get_chat_chain_ollama_chroma

from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
from django.views.decorators.csrf import csrf_exempt


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all().order_by('name')
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]


def hello_world(request):
    return HttpResponse("Hello, World!")


@csrf_exempt
def start_prompt(request):
    try:
        # required_params = ['param1', 'param2']
        data = json.loads(request.body)
        param1 = data.get('param1')
        param2 = data.get('param2')

    except ValidationError as e:
        return JsonResponse({'error': str(e)}, status=400)

    # 参数验证通过后，处理请求逻辑
    result = s_start_prompt(data)
    return HttpResponse(result)

@csrf_exempt
def store_files(request):
    try:
        pdf_files = request.FILES.getlist('files')
    except ValidationError as e:
        return JsonResponse({'error': str(e)}, status=400)

    # 参数验证通过后，处理请求逻辑
    result = s_store_file(pdf_files)
    return HttpResponse(result)

@csrf_exempt
def get_chat_chain(request):
    try:
        data = json.loads(request.body)
        # vector_store = data.get('vector_store')
        user_input = data.get('user_input')
    except ValidationError as e:
        return JsonResponse({'error': str(e)}, status=400)

    # 参数验证通过后，处理请求逻辑
    result = s_get_chat_chain(data)

    return HttpResponse(result)

@csrf_exempt
def store_file_ollama(request):
    pdf_files = request.FILES.getlist('files')

    try:
        result = s_store_file_ollama(pdf_files)
        # result = s_store_file_ollama_chroma(pdf_files)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)
    return HttpResponse(result)

@csrf_exempt
def get_chat_chain_ollama(request):
    data = json.loads(request.body)
    # vector_store = data.get('vector_store')
    result = s_get_chat_chain_ollama(data)
    # result = s_get_chat_chain_ollama_chroma(data)
    return HttpResponse(result)